<?php

namespace haibao\jiepai\business;

use \haibao\jiepai\data\Booth as BoothData;
use \haibao\jiepai\data\Article as ArticleData;
use haibao\classlibrary\jiepai\AppStaticConfig;

class Booth extends Base
{

    /**
     * @var $_instance
     */
    private static $_instance;

    /**
     * instance()
     */
    private static function instance()
    {
        if (!self::$_instance) {
            self::$_instance = new BoothData();
        }
        return self::$_instance;
    }

    public static function delPopularTag($tagId, $type = \haibao\jiepai\model\data\booth\CmsBlockList::TYPE_TAG)
    {
        self::instance()->delPopularTag($tagId, $type);
    }

    public static function recoverPopularTag($tagId, $type = \haibao\jiepai\model\data\booth\CmsBlockList::TYPE_TAG)
    {
        self::instance()->recoverPopularTag($tagId, $type);
    }

    public static function getBlockListByFilter($filter)
    {
        return self::instance()->getAll($filter);
    }

    /**
     * 处理头条焦点
     */
    public static function updateFocusStatus()
    {
        return self::instance()->updateFocusStatus();
    }

    /**
     * 焦点图
     */
    public static function getFocusList()
    {
        return self::instance()->getFocusList();
    }

    /**
     * 头条-置顶位
     * @param array $option
     */
    public static function getHeadFocusList($option = array())
    {
        return self::instance()->getHeadFocusList($option = array());
    }

    /**
     * 头条信息流位
     */
    public static function GetHomeFocusList()
    {
        return self::instance()->GetHomeFocusList();

    }


    public static function getSpecialColumnInfo($columnId)
    {

        if (!$columnId) {
            throw new BusinessException('栏目ID不为空');
        }

        return self::instance()->getSpecialColumnInfo((int)$columnId);
    }

    public static function getSpecialColumnArticles($columnId, $cursor = null, $userId = 0)
    {
        if (!$columnId) {
            throw new BusinessException('栏目ID不为空');
        }

        $isEditor = 0;
        if ($userId) {
            $data = new ArticleData();
            $isEditor = $data->IsEditor($userId);
        }
        return self::instance()->getSpecialColumnArticles((int)$columnId, $cursor, $isEditor);
    }

    public static function getWeeklyPersonInfo($articleIds)
    {
        $list = self::instance()->getWeeklyPersonInfo($articleIds);
        $newList = array();
        if ($list) {
            $celebrityIds = array();
            foreach ($list as $celebrityid) {
                $celebrityIds[] = $celebrityid;
            }
            $selArr = array(
                \haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_ID,
                \haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_NAME_CN,
                \haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_NAME_EN,
                \haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_STAR_TYPES,
            );
            $celebrityModels = \haibao\jiepai\business\Fashionista::getCelebrityModels($celebrityIds, $selArr, false);
            if ($celebrityModels) {
                foreach ($celebrityModels as $key => $model) {
                    //身份/职业
                    $Role = '';
                    if (!empty($model->StarTypes)) {
                        $temp = array();
                        $starTypes = $model->StarTypes;
                        if (!is_array($model->StarTypes)) $starTypes = explode(',', $model->StarTypes);
                        $typeArr = self::$defaultType;
                        foreach ($starTypes as $type) {
                            if (!empty($typeArr[preg_replace('/\[|\]/i', '', $type)])) {
                                $temp[] = $typeArr[preg_replace('/\[|\]/i', '', $type)];
                            }
                        }
                        $Role = $temp;
                    }
                    foreach ($list as $articleId => $celebrityId) {
                        if ($model->Id == $celebrityId) {
                            $tagName = isset($model->NameCn) ? $model->NameCn : $model->NameEn;
                            $newList[$articleId] = array('ArticleID' => $articleId, 'TagName' => $tagName, 'Role' => $Role);
                            break;
                        }
                    }
                }
            }
        }
        return $newList;
    }

    public static function getTopicById($topicId)
    {
        if (!$topicId) {
            throw new BusinessException('ID不为空');
        }

        return self::instance()->getTopicById($topicId);
    }

    public static function getTopicKeyRecArticles($topicId)
    {
        if (!$topicId) {
            throw new BusinessException('ID不为空');
        }

        return self::instance()->getTopicKeyRecArticles((int)$topicId);
    }

    public static function getHotRecommendBanners($version = '4.4.0')
    {

        return self::instance()->getHotRecommendBanners($version);
    }

    public static function getFindingsFashionistas()
    {

        return self::instance()->getFindingsFashionistas();
    }

    public static function getNineClockBooth($version)
    {

        return self::instance()->getNineClockBooth($version);
    }


    public static function getSpecialColumnList($userId, $version)
    {

        $isEditor = 0;
        if ($userId) {
            $data = new ArticleData();
            $isEditor = $data->IsEditor($userId);
        }
        return self::instance()->getSpecialColumnList($version, $isEditor);
    }

    public static function getFashionWallPapers()
    {

        return self::instance()->getFashionWallPapers();
    }

    public static function getCoverInfo()
    {
        return self::instance()->getCoverInfo();
    }

    public static function getTagRelation($tagId)
    {

        return self::instance()->getTagRelation((int)$tagId);
    }

    public static function getTagArticlesCount($tagId)
    {

        return self::instance()->getTagArticlesCount((int)$tagId);
    }

    public static function getTagPicture($tagId)
    {
        $pictures = self::instance()->getTagPicture((int)$tagId);

        $pictures = array_map(function ($picture) {
            if (!$picture['Picture']) {
                $picture = array();
            }
            return $picture;
        }, $pictures);
        $pictures = array_filter($pictures);
        if ($pictures) {
            return $pictures[array_rand($pictures)];
        }
        return array();
    }

    public static function getTagsArticles($fashionistaId, $cursor)
    {

        return self::instance()->getTagsArticles($fashionistaId, $cursor);
    }

    public static function getTagArticles($tagId, $cursor)
    {

        return self::instance()->getTagArticles($tagId, $cursor);
    }

    public static function getColumnById($columnId)
    {
        return self::instance()->getColumnById($columnId);
    }

    public static function getColumnArticles($columnId, $cursor = null)
    {

        return self::instance()->getColumnArticles((int)$columnId, $cursor);
    }

    //获取推荐栏目详情
    public static function getSecondColumns($columnId)
    {

        return self::instance()->getSecondColumns((int)$columnId);
    }

    public static function getHotRecommendTopics()
    {

        return self::instance()->getHotRecommendTopics();
    }

    public static function getHomeBanners()
    {

        $articleData = new ArticleData();
        /*$firstArticle = $articleData->getFirstArticleID();
        $firstArticleId = $firstArticle['ArticleID'];*/

        $homeHeadLineArticles = Article::getHomeHeadLineArticles();

        if ($homeHeadLineArticles) {
            $homeHeadLineArticles = json_decode(json_encode($homeHeadLineArticles), true);


            $homeHeadLineArticles = array_filter($homeHeadLineArticles);
            foreach ($homeHeadLineArticles as $key => $item) {
                if (intval($key) > 2) {
                    unset($homeHeadLineArticles[$key]);
                }
            }

            $homeHeadLineArticles = array_map(function ($article) {
                $article['FocusType'] = 1;
                $article['Ratio'] = 2;
                return $article;
            }, $homeHeadLineArticles);

            foreach ($homeHeadLineArticles as &$item) {
                if ($item['FocusType'] == 1) {
                    $item['ArticleID'] = (isset($item['ArticleID'])) ? $item['ArticleID'] : $item['TypeID'];
                    unset($item['Link']);
                    $item['ClickType'] = AppStaticConfig::getConfig(AppStaticConfig::APP_ARTICLE_HEADLINE);
                } else {
                    $item['Type'] = 3;
                    $item['AdUrl'] = $item['Link'];
                }
                unset($item['TypeID']);
                unset($item['FocusType']);
            }


            $advertArr = array();
            $advertListCache = \haibao\jiepai\business\Advert::getAdvertList();

            $firstAdvert = $secondAdvert = $thirdAdvert = array();
            $firstAdvert = array_filter($advertListCache, function ($advert) {
                return $advert['type'] == 3;
            });

            $secondAdvert = array_filter($advertListCache, function ($advert) {
                return $advert['type'] == 5;
            });

            $thirdAdvert = array_filter($advertListCache, function ($advert) {
                return $advert['type'] == 6;
            });

            if ($firstAdvert) {
                array_push($advertArr, current($firstAdvert));
            } else {
                array_push($advertArr, array());
            }
            if ($secondAdvert) {
                array_push($advertArr, current($secondAdvert));
            } else {
                array_push($advertArr, array());
            }
            if ($thirdAdvert) {
                array_push($advertArr, current($thirdAdvert));
            } else {
                array_push($advertArr, array());
            }

            foreach ($advertArr as $key => $advert) {
                if ($advert) {

                    $temp = array(
                        'AdvertID' => $advert['adId'],
                        'Title' => $advert['title'],
                        'Picture' => $advert['picUrl'],
                        'AdUrl' => ($advert['adUrl']) ? $advert['adUrl'] : null,
                        'PvMonitor' => $advert['pvMonitor'],
                        'BmsPvMonitor' => $advert['bmsPvMonitor'],
                        'Type' => 3
                    );
                    $advertArr[$key] = $temp;
                }
            }

            if ($advertArr[0]) {
                $temp = array($advertArr[0]);
                array_splice($homeHeadLineArticles, 1, 0, $temp);
            }

            if ($advertArr[1]) {
                $temp = array($advertArr[1]);
                array_splice($homeHeadLineArticles, 3, 0, $temp);
            }

            if ($advertArr[2]) {
                $temp = array($advertArr[2]);
                array_splice($homeHeadLineArticles, 5, 0, $temp);
            }

            if (count($homeHeadLineArticles) > 6) {
                $homeHeadLineArticles = array_slice($homeHeadLineArticles, 0, 6);
            }
        }
        return $homeHeadLineArticles;
    }

    public static function getTodayNineArticle()
    {

        return self::instance()->getTodayNineArticle();
    }

    //获取栏目热点
    public static function getColumnHots($columnId)
    {

        return self::instance()->getColumnHots($columnId);

    }

    //4.2.0获取文章列表
    public static function getColumnArticlesNew($columnInfo, $tagId, $cursor)
    {

        return self::instance()->getColumnArticlesNew($columnInfo, (int)$tagId, $cursor);
    }

    //430获取栏目配置标签
    public static function getColumnTags($columnId)
    {

        return self::instance()->getColumnTags((int)$columnId);
    }

    //获取栏目热点文章（4.3.0）
    public static function getHotestColumnArticle($columnId)
    {

        return self::instance()->getHotestColumnArticle((int)$columnId);
    }

    /**
     * 一周最点评文章列表
     */
    public static function getWeekReviewsArticles($nextCursor = null)
    {
        return self::instance()->getWeekReviewsArticles($nextCursor);
    }

    //430获取标签热门文章
    public static function getColumnTagArticles($hotestArticles, $hotTags, $columnId)
    {

        return self::instance()->getColumnTagArticles($hotestArticles, $hotTags, $columnId);
    }

    //根据ID获取TagID列表
    public static function getColumnTagList($tagId)
    {

        return self::instance()->getColumnTagList((int)$tagId);
    }

    // 计算最近流行存入缓存
    public static function setLatelyPopularCache()
    {

        $popularTags = self::instance()->getPopularTags();
        if ($popularTags) {

            $randIndex = array_rand($popularTags, 6);
            $finalArr = $fileIdList = array();
            foreach ($randIndex as $index) {

                list($arr, $fileIdList) = self::instance()->getTagPictureForLatelyPopular($popularTags[$index]['TagID'], $fileIdList);
                if ($arr) {

                    $tempArr = $popularTags[$index] + $arr;
                    unset($tempArr['count']);
                    if (isset($tempArr['ArticleID'])) {
                        unset($tempArr['ArticleID']);
                    }
                    unset($tempArr['FileID']);

                    array_push($finalArr, $tempArr);
                }
            }
            if ($finalArr) {
                \haibao\jiepai\cache\Crontab::set(\haibao\jiepai\cache\Crontab::LATELY_POPULAR_KEY, json_encode($finalArr));
            }
        }

    }

}